package com.beijiteshop.shop.ui.detail

import android.content.Context
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.recyclerview.widget.RecyclerView
import com.beijiteshop.shop.model.entity.CheckBoxEntity
import com.beijiteshop.shop.ui.detail.adapter.TextFlexBoxAdapter
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent

/**
 * @Author LiaoZhongKai
 * @Date 2021/3/5 13:53
 * @Description 创建纯文字流式布局列表,单选
 */
object TextFlexBoxRVHelper {

    /**
     * 设置RecyclerView为流式布局
     * @param data 数据源
     * @param itemResId item的background资源ID
     * @param itemTextColor item的文字颜色
     * @param listener item的点击事件
     */
    fun bind(context: Context, rv: RecyclerView,
             data: MutableList<CheckBoxEntity<String>>,
             @DrawableRes itemResId: Int,
             @ColorRes itemTextColor: Int,
             listener: (index: Int,data: String) -> Unit){
        val flexBoxManager = FlexboxLayoutManager(context).apply {
            flexDirection = FlexDirection.ROW
            flexWrap = FlexWrap.WRAP
            justifyContent = JustifyContent.FLEX_START
        }
        rv.apply {
            layoutManager = flexBoxManager
            adapter = TextFlexBoxAdapter(data,itemResId,itemTextColor).apply {
                setOnItemClickListener { _, _, position ->
                    //改变选中状态
                    val item = data.indexOfFirst { it.isSelected }
                    if (item >= 0){
                        data[item].isSelected = false
                        notifyItemChanged(item)
                    }
                    data[position].isSelected = true
                    notifyItemChanged(position)
                    listener.invoke(position,data[position].data)
                }
            }

        }

    }
}